<template>
  <div class="dashboard-container">
    <div class="dashboard-text">
      <div class="foodList">
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          :rules="rules"
          label-width="100px"
        >
          <div
            class="head-items"
            style="display: flex; justify-content: space-between"
          >
            <el-form-item label="名称" prop="name">
              <el-input
                v-model="ruleForm.name"
                class="input-width"
                placeholder="请填写菜品名称"
              />
            </el-form-item>
            <el-form-item
              label="菜品分类"
              prop="categoryId"
              style="float: right"
            >
              <el-select
                v-model="ruleForm.categoryId"
                placeholder="请选择菜品分类"
                class="input-width"
              >
                <el-option
                  v-for="item in categoryInfo"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </div>
          <el-form-item label="菜品价格" prop="price">
            <el-input
              v-model.number="ruleForm.price"
              class="input-width"
              placeholder="请设置菜品价格"
            />
          </el-form-item>
          <el-form-item label="口味做法配置" prop="flavors">
            <el-button type="warning" icon="el-icon-plus">添加口味</el-button>
          </el-form-item>
          <el-form-item label="菜品图片" prop="image">
            <el-upload
              class="avatar-uploader"
              action="#"
              :show-file-list="false"
              :http-request="uploadFoodImage"
            >
              <img
                v-if="ruleForm.image"
                :src="`${env}/common/download?name=${ruleForm.image}`"
                class="avatar"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="活动形式" prop="description">
            <el-input
              v-model="ruleForm.description"
              :rows="5"
              maxlength="200"
              show-word-limit
              type="textarea"
              placeholder="菜品描述，最长200个字符"
            />
          </el-form-item>
        </el-form>
      </div>
      <el-divider />
      <div class="buttons">
        <el-button @click="cancelAddFood">取消</el-button>
        <el-button type="primary" @click="toAddFood">保存</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import {
  uploadImages,
  getCategoryList,
  addDish,
  editDish,
} from "@/api/foodManage";
export default {
  data() {
    return {
      env: process.env.VUE_APP_BASE_API,
      categoryInfo: [],
      ruleForm: {
        name: "",
        categoryId: "",
        price: "",
        flavors: [],
        image: "",
        description: "",
        status: 1,
      },
      rules: {
        name: [
          { required: true, message: "请填写菜品名称", trigger: "blur" },
          { min: 1, message: "长度至少 1 个字符", trigger: "blur" },
        ],
        categoryId: [{ required: true }],
        price: [
          { required: true, message: "请设置菜品价格", trigger: "blur" },
          { type: "number", message: "价格必须为数字值", trigger: "blur" },
        ],
        image: [{ required: true, message: "请上传图片", trigger: "change" }],
      },
      fileList: [],
      dialogImageUrl: "",
      dialogVisible: false,
      disabled: false,
      // 图片文件
      uploadImg: "",
    };
  },
  computed: {
    foodMsg() {
      return JSON.parse(this.$route.query.msg);
    },
    isEdit() {
      return this.$route.query.isEdit === "1";
    },
  },
  created() {
    // 获取菜品分类列表
    this.getFoodList();
    // 接收修改参数
    if (this.isEdit) {
      this.fileList = [{ url: this.foodMsg.image }];
      this.ruleForm = this.foodMsg;
    }
  },
  methods: {
    // 获取菜品分类列表
    getFoodList() {
      getCategoryList().then((res) => {
        this.categoryInfo = { ...res.data };
      });
    },
    handleExceed() {
      this.$message.error("最多上传一张图片");
    },
    handleRemove(file, fileList) {
      this.fileList = fileList || [];
      this.ruleForm.image = fileList ? this.ruleForm.image : "";
    },
    // 图片上传
    uploadFoodImage(data) {
      const formData = new FormData();
      formData.append("file", data.file);
      uploadImages(formData).then((res) => {
        this.ruleForm.image = res.data;
      });
    },
    // 预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 取消添加
    cancelAddFood() {
      this.$router.push({ name: "foodManage" });
    },
    // 点击确认添加
    toAddFood() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (!this.isEdit) {
            addDish({ ...this.ruleForm, code: "" }).then((res) => {
              this.$router.push({ name: "foodManage" });
            });
          } else {
            // 防止将url都传入foodManage页面导致图片路径重复修改
            this.ruleForm.image = this.ruleForm.image.split("name=")[1];
            editDish({ ...this.ruleForm, code: "" }).then((res) => {
              this.$router.push({ name: "foodManage" });
            });
          }
        } else {
          this.$message.error("输入数据不合法");
        }
      });
    },
  },
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style lang="scss" scoped>
.foodList {
  width: 60%;
}
.buttons {
  margin-left: 40%;
}
.input-width {
  width: 300px;
}
</style>
